﻿using System.Collections.Generic;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System;
using System.IO;
using System.Windows;
using System.Windows.Controls;

namespace LunarSF.SHomeWorkshop.LunarMarkdownEditor
{
    /// <summary>
    /// 创建时间：2011年12月27日
    /// 创 建 者：　杨震宇
    /// 说    明：源自我的另一个项目《Lunar Concept》，2018年3月28日移植过来。
    /// 
    /// 主要用途：提供中、英文色彩名称到Brushe实例的转换。
    /// ★★★★★此类最有价值的是静态构造方法中的《色彩名称中英文对照表》！
    /// </summary>
    public static class BrushManager
    {
        #region 构造方法=====================================================================================================

        /// <summary>
        /// [构造方法]用于初始化brushesList列表，以便查找。
        /// 
        /// ——此类【最有价值】的部分就在此处！！！
        /// </summary>
        static BrushManager()
        {
            brushesList = new List<BrushItem>();

            brushesList.Add(new BrushItem(Brushes.AliceBlue, "AliceBlue", "爱丽丝蓝"));
            brushesList.Add(new BrushItem(Brushes.AntiqueWhite, "AntiqueWhite", "古董白"));
            brushesList.Add(new BrushItem(Brushes.Aqua, "Aqua", "水绿"));
            brushesList.Add(new BrushItem(Brushes.Aquamarine, "Aquamarine", "碧玉绿"));
            brushesList.Add(new BrushItem(Brushes.Azure, "Azure", "蔚蓝"));
            brushesList.Add(new BrushItem(Brushes.Beige, "Beige", "米色"));
            brushesList.Add(new BrushItem(Brushes.Bisque, "Bisque", "乳脂色"));
            brushesList.Add(new BrushItem(Brushes.Black, "Black", "黑色"));
            brushesList.Add(new BrushItem(Brushes.BlanchedAlmond, "BlanchedAlmond", "白杏色"));
            brushesList.Add(new BrushItem(Brushes.Blue, "Blue", "蓝色"));
            brushesList.Add(new BrushItem(Brushes.BlueViolet, "BlueViolet", "蓝紫罗兰色"));
            brushesList.Add(new BrushItem(Brushes.Brown, "Brown", "棕色"));
            brushesList.Add(new BrushItem(Brushes.BurlyWood, "BurlyWood", "坚树色"));
            brushesList.Add(new BrushItem(Brushes.CadetBlue, "CadetBlue", "军校蓝"));
            brushesList.Add(new BrushItem(Brushes.Chartreuse, "Chartreuse", "查特酒绿"));
            brushesList.Add(new BrushItem(Brushes.Chocolate, "Chocolate", "巧克力色"));
            brushesList.Add(new BrushItem(Brushes.Coral, "Coral", "珊瑚色"));
            brushesList.Add(new BrushItem(Brushes.CornflowerBlue, "CornflowerBlue", "矢车菊蓝"));
            brushesList.Add(new BrushItem(Brushes.Cornsilk, "Cornsilk", "玉米色"));
            brushesList.Add(new BrushItem(Brushes.Crimson, "Crimson", "猩红"));
            brushesList.Add(new BrushItem(Brushes.Cyan, "Cyan", "青色"));
            brushesList.Add(new BrushItem(Brushes.DarkBlue, "DarkBlue", "深蓝"));
            brushesList.Add(new BrushItem(Brushes.DarkCyan, "DarkCyan", "深青"));
            brushesList.Add(new BrushItem(Brushes.DarkGoldenrod, "DarkGoldenrod", "深金菊色"));
            brushesList.Add(new BrushItem(Brushes.DarkGray, "DarkGray", "深灰"));
            brushesList.Add(new BrushItem(Brushes.DarkGreen, "DarkGreen", "深绿"));
            brushesList.Add(new BrushItem(Brushes.DarkKhaki, "DarkKhaki", "深卡其布色"));
            brushesList.Add(new BrushItem(Brushes.DarkMagenta, "DarkMagenta", "深洋红"));
            brushesList.Add(new BrushItem(Brushes.DarkOliveGreen, "DarkOliveGreen", "深橄榄绿"));
            brushesList.Add(new BrushItem(Brushes.DarkOrange, "DarkOrange", "深橙色"));
            brushesList.Add(new BrushItem(Brushes.DarkOrchid, "DarkOrchid", "深兰花紫"));
            brushesList.Add(new BrushItem(Brushes.DarkRed, "DarkRed", "深红"));
            brushesList.Add(new BrushItem(Brushes.DarkSalmon, "DarkSalmon", "鲑鱼色"));
            brushesList.Add(new BrushItem(Brushes.DarkSeaGreen, "DarkSeaGreen", "深海绿"));
            brushesList.Add(new BrushItem(Brushes.DarkSlateBlue, "DarkSlateBlue", "深石板蓝"));
            brushesList.Add(new BrushItem(Brushes.DarkSlateGray, "DarkSlateGray", "深石板灰"));
            brushesList.Add(new BrushItem(Brushes.DarkTurquoise, "DarkTurquoise", "深宝石绿"));
            brushesList.Add(new BrushItem(Brushes.DarkViolet, "DarkViolet", "深紫罗兰色"));
            brushesList.Add(new BrushItem(Brushes.DeepPink, "DeepPink", "深粉色"));
            brushesList.Add(new BrushItem(Brushes.DeepSkyBlue, "DeepSkyBlue", "深天蓝"));
            brushesList.Add(new BrushItem(Brushes.DimGray, "DimGray", "暗灰"));
            brushesList.Add(new BrushItem(Brushes.DodgerBlue, "DodgerBlue", "道奇蓝"));
            brushesList.Add(new BrushItem(Brushes.Firebrick, "Firebrick", "耐火砖色"));
            brushesList.Add(new BrushItem(Brushes.FloralWhite, "FloralWhite", "花白"));
            brushesList.Add(new BrushItem(Brushes.ForestGreen, "ForestGreen", "森林绿"));
            brushesList.Add(new BrushItem(Brushes.Fuchsia, "Fuchsia", "灯笼海棠色"));
            brushesList.Add(new BrushItem(Brushes.Gainsboro, "Gainsboro", "庚斯博罗灰"));
            brushesList.Add(new BrushItem(Brushes.GhostWhite, "GhostWhite", "幽灵白"));
            brushesList.Add(new BrushItem(Brushes.Gold, "Gold", "金色"));
            brushesList.Add(new BrushItem(Brushes.Goldenrod, "Goldenrod", "金菊黄"));
            brushesList.Add(new BrushItem(Brushes.Gray, "Gray", "灰色"));
            brushesList.Add(new BrushItem(Brushes.Green, "Green", "绿色"));
            brushesList.Add(new BrushItem(Brushes.GreenYellow, "GreenYellow", "绿黄"));
            brushesList.Add(new BrushItem(Brushes.Honeydew, "Honeydew", "蜜色"));
            brushesList.Add(new BrushItem(Brushes.HotPink, "HotPink", "热粉色"));
            brushesList.Add(new BrushItem(Brushes.IndianRed, "IndianRed", "印度红"));
            brushesList.Add(new BrushItem(Brushes.Indigo, "Indigo", "靛青"));
            brushesList.Add(new BrushItem(Brushes.Ivory, "Ivory", "象牙色"));
            brushesList.Add(new BrushItem(Brushes.Khaki, "Khaki", "卡其布色"));
            brushesList.Add(new BrushItem(Brushes.Lavender, "Lavender", "熏衣草色"));
            brushesList.Add(new BrushItem(Brushes.LavenderBlush, "LavenderBlush", "熏衣草红"));
            brushesList.Add(new BrushItem(Brushes.LawnGreen, "LawnGreen", "草坪绿"));
            brushesList.Add(new BrushItem(Brushes.LemonChiffon, "LemonChiffon", "柠檬绸色"));
            brushesList.Add(new BrushItem(Brushes.LightBlue, "LightBlue", "浅蓝"));
            brushesList.Add(new BrushItem(Brushes.LightCoral, "LightCoral", "浅珊瑚色"));
            brushesList.Add(new BrushItem(Brushes.LightCyan, "LightCyan", "浅青色"));
            brushesList.Add(new BrushItem(Brushes.LightGoldenrodYellow, "LightGoldenrodYellow", "浅金菊黄"));
            brushesList.Add(new BrushItem(Brushes.LightGray, "LightGray", "浅灰"));
            brushesList.Add(new BrushItem(Brushes.LightGreen, "LightGreen", "浅绿"));
            brushesList.Add(new BrushItem(Brushes.LightPink, "LightPink", "浅粉色"));
            brushesList.Add(new BrushItem(Brushes.LightSalmon, "LightSalmon", "浅鲑鱼肉色"));
            brushesList.Add(new BrushItem(Brushes.LightSeaGreen, "LightSeaGreen", "浅海绿"));
            brushesList.Add(new BrushItem(Brushes.LightSkyBlue, "LightSkyBlue", "浅海蓝"));
            brushesList.Add(new BrushItem(Brushes.LightSlateGray, "LightSlateGray", "浅石板灰"));
            brushesList.Add(new BrushItem(Brushes.LightSteelBlue, "LightSteelBlue", "浅钢蓝"));
            brushesList.Add(new BrushItem(Brushes.LightYellow, "LightYellow", "浅黄"));
            brushesList.Add(new BrushItem(Brushes.Lime, "Lime", "酸橙色"));
            brushesList.Add(new BrushItem(Brushes.LimeGreen, "LimeGreen", "酸橙绿"));
            brushesList.Add(new BrushItem(Brushes.Linen, "Linen", "亚麻布色"));
            brushesList.Add(new BrushItem(Brushes.Magenta, "Magenta", "洋红"));
            brushesList.Add(new BrushItem(Brushes.Maroon, "Maroon", "栗色"));
            brushesList.Add(new BrushItem(Brushes.MediumAquamarine, "MediumAquamarine", "中碧玉绿"));
            brushesList.Add(new BrushItem(Brushes.MediumBlue, "MediumBlue", "中蓝"));
            brushesList.Add(new BrushItem(Brushes.MediumOrchid, "MediumOrchid", "中兰花紫"));
            brushesList.Add(new BrushItem(Brushes.MediumPurple, "MediumPurple", "中紫"));
            brushesList.Add(new BrushItem(Brushes.MediumSeaGreen, "MediumSeaGreen", "中海绿"));
            brushesList.Add(new BrushItem(Brushes.MediumSlateBlue, "MediumSlateBlue", "中石板蓝"));
            brushesList.Add(new BrushItem(Brushes.MediumSpringGreen, "MediumSpringGreen", "中春绿"));
            brushesList.Add(new BrushItem(Brushes.MediumTurquoise, "MediumTurquoise", "中宝石绿"));
            brushesList.Add(new BrushItem(Brushes.MediumVioletRed, "MediumVioletRed", "中紫罗兰红"));
            brushesList.Add(new BrushItem(Brushes.MidnightBlue, "MidnightBlue", "午夜蓝"));
            brushesList.Add(new BrushItem(Brushes.MintCream, "MintCream", "薄荷奶油色"));
            brushesList.Add(new BrushItem(Brushes.MistyRose, "MistyRose", "薄雾玫瑰色"));
            brushesList.Add(new BrushItem(Brushes.Moccasin, "Moccasin", "鹿皮色"));
            brushesList.Add(new BrushItem(Brushes.NavajoWhite, "NavajoWhite", "纳瓦白/土著白"));
            brushesList.Add(new BrushItem(Brushes.Navy, "Navy", "海军蓝"));
            brushesList.Add(new BrushItem(Brushes.OldLace, "OldLace", "旧蕾丝色"));
            brushesList.Add(new BrushItem(Brushes.Olive, "Olive", "橄榄色"));
            brushesList.Add(new BrushItem(Brushes.OliveDrab, "OliveDrab", "橄榄褐"));
            brushesList.Add(new BrushItem(Brushes.Orange, "Orange", "橙色"));
            brushesList.Add(new BrushItem(Brushes.OrangeRed, "OrangeRed", "橙红"));
            brushesList.Add(new BrushItem(Brushes.Orchid, "Orchid", "兰花紫"));
            brushesList.Add(new BrushItem(Brushes.PaleGoldenrod, "PaleGoldenrod", "灰金菊色"));
            brushesList.Add(new BrushItem(Brushes.PaleGreen, "PaleGreen", "灰绿"));
            brushesList.Add(new BrushItem(Brushes.PaleTurquoise, "PaleTurquoise", "灰宝石绿"));
            brushesList.Add(new BrushItem(Brushes.PaleVioletRed, "PaleVioletRed", "灰紫罗兰红"));
            brushesList.Add(new BrushItem(Brushes.PapayaWhip, "PapayaWhip", "番木瓜色"));
            brushesList.Add(new BrushItem(Brushes.PeachPuff, "PeachPuff", "桃色"));
            brushesList.Add(new BrushItem(Brushes.Peru, "Peru", "秘鲁色"));
            brushesList.Add(new BrushItem(Brushes.Pink, "Pink", "粉红"));
            brushesList.Add(new BrushItem(Brushes.Plum, "Plum", "李色"));
            brushesList.Add(new BrushItem(Brushes.PowderBlue, "PowderBlue", "粉蓝"));
            brushesList.Add(new BrushItem(Brushes.Purple, "Purple", "紫色"));
            brushesList.Add(new BrushItem(Brushes.Red, "Red", "红色"));
            brushesList.Add(new BrushItem(Brushes.RosyBrown, "RosyBrown", "玫瑰棕色"));
            brushesList.Add(new BrushItem(Brushes.RoyalBlue, "RoyalBlue", "皇室蓝"));
            brushesList.Add(new BrushItem(Brushes.SaddleBrown, "SaddleBrown", "重褐色"));
            brushesList.Add(new BrushItem(Brushes.Salmon, "Salmon", "鲑鱼肉色"));
            brushesList.Add(new BrushItem(Brushes.SandyBrown, "SandyBrown", "沙棕色"));
            brushesList.Add(new BrushItem(Brushes.SeaGreen, "SeaGreen", "海绿"));
            brushesList.Add(new BrushItem(Brushes.SeaShell, "SeaShell", "海贝色"));
            brushesList.Add(new BrushItem(Brushes.Sienna, "Sienna", "黄土赭"));
            brushesList.Add(new BrushItem(Brushes.Silver, "Silver", "银白"));
            brushesList.Add(new BrushItem(Brushes.SkyBlue, "SkyBlue", "天蓝"));
            brushesList.Add(new BrushItem(Brushes.SlateBlue, "SlateBlue", "石板蓝"));
            brushesList.Add(new BrushItem(Brushes.SlateGray, "SlateGray", "石板灰"));
            brushesList.Add(new BrushItem(Brushes.Snow, "Snow", "雪色"));
            brushesList.Add(new BrushItem(Brushes.SpringGreen, "SpringGreen", "春绿"));
            brushesList.Add(new BrushItem(Brushes.SteelBlue, "SteelBlue", "钢蓝"));
            brushesList.Add(new BrushItem(Brushes.Tan, "Tan", "茶色"));
            brushesList.Add(new BrushItem(Brushes.Teal, "Teal", " 水鸭绿"));
            brushesList.Add(new BrushItem(Brushes.Thistle, "Thistle", "蓟色"));
            brushesList.Add(new BrushItem(Brushes.Tomato, "Tomato", "番茄色"));
            brushesList.Add(new BrushItem(Brushes.Transparent, "Transparent", "透明色"));
            brushesList.Add(new BrushItem(Brushes.Turquoise, "Turquoise", "宝石绿"));
            brushesList.Add(new BrushItem(Brushes.Violet, "Violet", "紫罗兰色"));
            brushesList.Add(new BrushItem(Brushes.Wheat, "Wheat", "小麦色"));
            brushesList.Add(new BrushItem(Brushes.White, "White", "白色"));
            brushesList.Add(new BrushItem(Brushes.WhiteSmoke, "WhiteSmoke", "白烟色"));
            brushesList.Add(new BrushItem(Brushes.Yellow, "Yellow", "黄色"));
            brushesList.Add(new BrushItem(Brushes.YellowGreen, "YellowGreen", "黄绿"));

        }

        /// <summary>
        /// 随机数种子。创建多个种子可能造成返回同一个随机数。
        /// 而使用同一个随机数种子，返回同一个随机数的概率很低。
        /// </summary>
        private static Random random;

        /// <summary>
        /// 随机取纯色。若取不出，默认返回黑色。不会返回null。
        /// </summary>
        /// <returns>纯色画刷。</returns>
        public static SolidColorBrush GetRandomSolidBrush()
        {
            if (BrushManager.brushesList == null || BrushManager.brushesList.Count <= 0)
            {
                return Brushes.Black;
            }

            if (BrushManager.random == null)
            {
                BrushManager.random = new Random();
            }

            int newIndex;

            SolidColorBrush scb = null;
            do
            {
                newIndex = random.Next(75, 214);
                if (newIndex >= 0 && newIndex < BrushManager.brushesList.Count)
                {
                    scb = BrushManager.brushesList[newIndex].Brush as SolidColorBrush;
                }
            } while (scb == null);

            return scb;
        }

        #endregion

        #region 字段与属性===================================================================================================
        
        /// <summary>
        /// 内部使用，不公开。在静态构造方法中初始化其中的内容。
        /// </summary>
        private static List<BrushItem> brushesList;

        #endregion

        #region 方法=========================================================================================================

        /// <summary>
        /// GetBrushByEnglishName(string enName)方法的别名。
        /// </summary>
        /// <param name="enName">画刷的英文名称。</param>
        /// <returns>如果找到，就返回画刷；否则返回null。</returns>
        public static Brush GetBrush(string enName)
        {
            return GetBrushByEnglishName(enName);
        }

        /// <summary>
        /// [静态方法]根据给出的英文名称取色彩Brush对象（Brushes类的某个属性）。
        /// 如果不支持所给的名称，会返回null。
        /// </summary>
        /// <param name="enName">Brush的英文名称。</param>
        /// <returns>返回Brush。</returns>
        public static Brush GetBrushByEnglishName(string enName)
        {
            if (enName == null) return null;

            if (enName.StartsWith("sc#"))
            {
                try
                {
                    Color color = (Color)ColorConverter.ConvertFromString(enName);
                    SolidColorBrush newColorBrush = new SolidColorBrush(color);
                    return newColorBrush;
                }
                catch
                {
                    return null;
                }
            }

            foreach (BrushItem bi in brushesList)
            {
                if (bi.EnName.ToLower() == enName.ToLower()) return bi.Brush;
            }

            return null;
        }

        /// <summary>
        /// [静态方法]根据所给出的中文名称取色彩Brush对象（Brushes类的某个属性）。
        /// 如果不支持所给的名称，会返回null。
        /// </summary>
        /// <param name="cnName">Brushes的中文名称（必须是在本类静态构造方法中定义的名称）。</param>
        /// <returns>返回Brush。</returns>
        public static Brush GetBrushByChineseName(string cnName)
        {
            if (cnName == null) return null;

            if (cnName.StartsWith("sc#"))
            {
                try
                {
                    Color color = (Color)ColorConverter.ConvertFromString(cnName);
                    SolidColorBrush newColorBrush = new SolidColorBrush(color);
                    return newColorBrush;
                }
                catch
                {
                    return null;
                }
            }

            foreach (BrushItem bi in brushesList)
            {
                if (bi.CnName == cnName) return bi.Brush;
            }

            return null;
        }

        /// <summary>
        /// [静态方法]取Brush的中文名称。
        /// 名称修改自网上的中英文色彩名称对照表。
        /// </summary>
        /// <param name="brush">只能传入Brushes类中定义的Brush。</param>
        /// <returns></returns>
        public static string GetChineseName(Brush brush)
        {
            if (brush == null) return null;
            if (brush is ImageBrush) return "图像画刷";

            foreach (BrushItem bi in brushesList)
            {
                if (brush == bi.Brush) return bi.CnName;
            }

            SolidColorBrush sbsh = brush as SolidColorBrush;
            if (sbsh != null)
            {
                return sbsh.Color.ToString();//返回#00FFFFFF之类字串。
            }

            return null;
        }

        /// <summary>
        /// [静态方法]根据Brush的英文名称取Brush的中文名称。
        /// 失败会返回null。
        /// </summary>
        /// <param name="brushEnName">只能传入Brushes类中定义的Brush的英文名称。</param>
        /// <returns>失败会返回null。</returns>
        public static string GetChineseName(string brushEnName)
        {
            if (brushEnName == null) return null;

            if (brushEnName.StartsWith("sc#")) return brushEnName;//原样返回。

            foreach (BrushItem bi in brushesList)
            {
                if (brushEnName == bi.EnName) return bi.CnName;
            }

            return null;
        }

        /// <summary>
        /// [静态方法]即GetEnglishName(Brush brush)方法。
        /// </summary>
        public static string GetName(Brush brush)
        {
            return GetEnglishName(brush);
        }

        /// <summary>
        /// [静态方法]取Brush的英文名称。是.net Brushes类内置的属性名。
        /// ——提供的名称必须是Brushes类支持的色彩名称。如果失败，返回null。
        /// </summary>
        /// <param name="brush">只能传入Brushes类中定义的Brush。</param>
        /// <returns>返回Brush对象。失败返回null。</returns>
        public static string GetEnglishName(Brush brush)
        {
            if (brush == null) return null;
            if (brush is ImageBrush) return typeof(ImageBrush).Name;
            
            foreach (BrushItem bi in brushesList)
            {
                if (brush == bi.Brush) return bi.EnName;
            }

            SolidColorBrush sbsh = brush as SolidColorBrush;
            if (sbsh != null)
            {
                return sbsh.Color.ToString();//返回#00FFFFFF之类字串。
            }

            return null;
        }

        /// <summary>
        /// [静态方法]根据中文名称取Brush的英文名称。
        /// </summary>
        /// <param name="brushCnName">只能传入Brushes类中定义的Brush的中文名称。</param>
        /// <returns>失败会返回null。</returns>
        public static string GetEnglishName(string brushCnName)
        {
            if (brushCnName == null) return null;

            if (brushCnName.StartsWith("sc#")) return brushCnName;//原样返回。

            foreach (BrushItem bi in brushesList)
            {
                if (brushCnName == bi.CnName) return bi.EnName;
            }

            return null;
        }

        /// <summary>
        /// 检查传入的Brush是否合法的Brush（Brushes类预定的某个SolidBrush）或者此类自定义的某些画刷。
        /// </summary>
        public static bool IsValidateBrush(Brush brush)
        {
            if (brush == null) return false;

            SolidColorBrush sbsh = brush as SolidColorBrush;
            if (sbsh != null)
            {
                return true;
            }

            foreach (BrushItem bi in brushesList)
            {
                if (bi.Brush == brush) return true;
            }

            return false;
        }

        /// <summary>
        /// 将提交的字符串转换为Brush对象。
        /// 
        /// 如果字符串以“s”开头，则转换为SolicColorBrush；★这里有个特例：sTransparent，它会直接返回默认的图像画刷。
        /// 如果字符串以“i”开头，则转换为ImageBrush。
        /// 
        /// 如果字符串不合法，则返回默认的图像画刷。
        /// </summary>
        /// <param name="sourceText"></param>
        /// <returns></returns>
        public static Brush Parse(string sourceText)
        {
            if (sourceText == null || sourceText.Length <= 0) return null;

            if (sourceText == "sTransparent" || sourceText == "Transparent" || sourceText == "iTransparent")
            {
                return null;
            }

            if (sourceText.StartsWith("i"))
            {
                string imgDataText = sourceText.Substring(1);
                System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();

                if (imgDataText != null && imgDataText.Length > 0)
                {
                    byte[] b = Convert.FromBase64String(imgDataText);
                    bmp.BeginInit();
                    bmp.StreamSource = new MemoryStream(b);
                    bmp.EndInit();

                    ImageBrush iBsh = new ImageBrush(bmp) { Stretch = System.Windows.Media.Stretch.UniformToFill };
                    iBsh.ViewportUnits = System.Windows.Media.BrushMappingMode.Absolute;
                    iBsh.Viewport = new System.Windows.Rect(0, 0, iBsh.ImageSource.Width, iBsh.ImageSource.Height);
                    return iBsh;

                }
                else return null;
            }

            if (sourceText.StartsWith("s"))
            {
                return BrushManager.GetBrushByEnglishName(sourceText.Substring(1)); ;
            }

            return null;
        }

        /// <summary>
        /// 将指定的图片文件转换成为一个Base64的字符串，并以“i”开头。
        /// </summary>
        /// <param name="imageFilePath">图片文件的完整路径。</param>
        /// <returns>图片转换成的Base64字符串（以“i”开头）。</returns>
        public static string ParseToText(string imageFilePath, out ImageBrush iBsh, TileMode tileMode = TileMode.FlipXY)
        {
            string filename = imageFilePath;

            System.IO.FileInfo fileInfo = new FileInfo(filename);

            if (fileInfo.Exists == false)
            {
                LMessageBox.Show("发生意外，指定的图片文件不存在！", Globals.AppName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                iBsh = null;
                return string.Empty;
            }

            if (fileInfo.Length <= 2097152)//将图片限制在2MB以内
            {
                System.Drawing.Image fileImg = System.Drawing.Image.FromFile(filename);
                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    try
                    {
                        if (fileInfo.Extension.ToLower() == ".png")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                        }
                        else if (fileInfo.Extension.ToLower() == ".jpg" || fileInfo.Extension.ToLower() == ".jpeg")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
                        }
                        else if (fileInfo.Extension.ToLower() == ".gif")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Gif);
                        }
                        else if (fileInfo.Extension.ToLower() == ".tiff")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Tiff);
                        }
                        else if (fileInfo.Extension.ToLower() == ".bmp")
                        {
                            fileImg.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
                        }
                        else
                        {
                            iBsh = null;
                            return string.Empty;//不能识别的文件格式。
                        }

                        byte[] b = stream.GetBuffer();
                        string imgDataText = Convert.ToBase64String(b);

                        ImageBrush newLoadedImageBrush = new ImageBrush()
                        {
                            ImageSource = new BitmapImage(new Uri(filename, UriKind.Relative)),
                            ViewportUnits = System.Windows.Media.BrushMappingMode.Absolute,
                            Viewport = new Rect(0, 0, fileImg.Width, fileImg.Height),
                        };

                        newLoadedImageBrush.TileMode = tileMode;

                        iBsh = newLoadedImageBrush;

                        return "i" + imgDataText;
                    }
                    catch (System.Runtime.InteropServices.ExternalException ex)
                    {
                        LMessageBox.Show("该图片文件后缀名有问题，或图片被损坏。" +
                            "该图像以错误的图像格式后缀名保存！\r\n" + ex.Message + ex.StackTrace,
                            Globals.AppName, MessageBoxButton.OK, MessageBoxImage.Warning);
                        iBsh = null;
                        return string.Empty;
                    }
                }
            }
            else
            {
                LMessageBox.Show("所选择的图片文件过大！" +
                    "为防止文档体积过分庞大，本图片框只支持文件尺寸在 2MB 以下的图片！" +
                    "请将图片加工一下或另选一张图片。", Globals.AppName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                iBsh = null;
                return string.Empty;
            }
        }

        /// <summary>
        /// SolidColorBrush转换成相应的字符串。注意：以“s”开头。
        /// 
        /// 如果不合法，生成空字符串。
        /// </summary>
        /// <param name="srcBrush">画刷。</param>
        /// <returns>生成的文本。</returns>
        public static string ParseToText(Brush srcBrush)
        {
            SolidColorBrush scb = srcBrush as SolidColorBrush;
            if (scb != null)
            {
                return "s" + BrushManager.GetName(scb);
            }

            return string.Empty;
        }

        #endregion
    }

    /// <summary>
    /// 此类只用于BrushManager。
    /// </summary>
    internal class BrushItem
    {
        /// <summary>
        /// [构造方法]
        /// </summary>
        /// <param name="bsh">Brush。</param>
        /// <param name="enName">Brush的中文名称。</param>
        /// <param name="cnName">Brush的英文名称。</param>
        public BrushItem(Brush bsh, string enName, string cnName)
        {
            this.brush = bsh;
            this.enName = enName;
            this.cnName = cnName;
        }

        private Brush brush = Brushes.Transparent;

        /// <summary>
        /// 默认是透明色。
        /// </summary>
        public Brush Brush
        {
            get { return brush; }
            set { brush = value; }
        }

        private string enName = "Transparent";
        /// <summary>
        /// Brush的英文名称。
        /// </summary>
        public string EnName
        {
            get { return enName; }
        }

        private string cnName = "透明色";
        /// <summary>
        /// Brush的中文名称。这些名称是参考网络上的色彩名称的译法修改而来。
        /// </summary>
        public string CnName
        {
            get { return cnName; }
        }
    }
}
